package com.huawei.app.demo.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.huawei.app.demo.AppConstants;
import com.huawei.app.demo.MainActivity;
import com.huawei.app.demo.MsgHandler;
import com.huawei.app.demo.R;
import com.huawei.app.demo.service.VideoFloatingService;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.demo.util.NetworkUtils;
import com.huawei.app.demo.video.AvcDecoderTask;
import com.huawei.app.demo.video.AvcEncoderTask;
import com.huawei.app.demo.video.ImgBuffer;
import com.huawei.app.demo.video.ReceiverTask;
import com.huawei.app.demo.video.SenderTask;
import com.huawei.app.demo.video.ShareScreenRecvSurfaceCallback;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 视频
 *
 * @since 2021-01-20
 */
public class VideoFragment extends CustomFragment {

    private static final String TAG = VideoFragment.class.getSimpleName();
    private Context context;
    private View rootView;
    private EditText remoteIp;

    // 截屏录屏
    private MediaProjectionManager mediaProjectionManager;
    private MediaProjection mediaProjection;
    private VirtualDisplay shareScreenVirtualDisplay;
    private VirtualDisplay shareScreenSendVirtualDisplay;

    // 编码任务
    private AvcEncoderTask encoderTask;
    private SenderTask senderTask;
    public ArrayBlockingQueue<ImgBuffer> senderQueue = new ArrayBlockingQueue<>(30*60*5); // 缓存5分钟数据(每秒30帧 * 60秒 * 5)

    // 解码任务
    private ReceiverTask receiverTask;
    private AvcDecoderTask decoderTask;
    public ArrayBlockingQueue<ImgBuffer> receiverQueue = new ArrayBlockingQueue<>(30*60*5); // 缓存5分钟数据

    // 后台服务
    private VideoFloatingService.MyBinder binder;
    private ServiceConnection serviceConn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (VideoFloatingService.MyBinder)service;
            binder.setContext(VideoFragment.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    public String getTitle() {
        return "视频";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_video, container, false);

        // init view
        Button prepareCaptureScreen = rootView.findViewById(R.id.prepareCaptureScreen);
        Button prepareShareScreen = rootView.findViewById(R.id.prepareShareScreen);
        Button prepareShareScreenToRemote = rootView.findViewById(R.id.prepareShareScreenToRemote);
        this.remoteIp = rootView.findViewById(R.id.remoteIp);

        // init event
        prepareCaptureScreen.setOnClickListener(this);
        prepareShareScreen.setOnClickListener(this);
        prepareShareScreenToRemote.setOnClickListener(this);

        // init data
        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                String ip = NetworkUtils.getDeviceIp(true);
                if (ip.isEmpty()) {
                    ip = NetworkUtils.getDeviceIp(false);
                }

                Message msg = Message.obtain();
                msg.what = MsgHandler.UPDATE_EDIT_TEXT_VALUE;
                msg.arg1 = R.id.remoteIp;
                msg.obj = ip;
                msgHandler.sendMessage(msg);
            }
        });
        return rootView;
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.prepareCaptureScreen: {
                prepareCaptureScreen();
                break;
            }
            case R.id.prepareShareScreen: {
                prepareShareScreen();
                break;
            }
            case R.id.prepareShareScreenToRemote: {
                prepareShareScreenToRemote();
                break;
            }
            default: {
                break;
            }
        }
    }

    /**
     * 准备截屏 - 申请截屏权限
     */
    public void prepareCaptureScreen() {
        LogUtils.getInstance().i(TAG, "prepareCaptureScreen begin.");

        if (mediaProjectionManager == null || mediaProjection == null) {
            // 申请截屏权限
            mediaProjectionManager = (MediaProjectionManager)context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            Intent intent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(intent, AppConstants.REQUEST_CAPTURE_SCREEN_CODE);
        } else {
            reqCaptureScreenFloatingPermission();
        }

        LogUtils.getInstance().i(TAG, "prepareCaptureScreen end.");
    }

    /**
     * 准备截屏 - 申请悬浮窗权限
     */
    private void reqCaptureScreenFloatingPermission() {
        if (!Settings.canDrawOverlays(context)) {
            // 申请悬浮窗权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            startActivityForResult(intent, AppConstants.REQUEST_CAPTURE_FLOATING_CODE);
        } else {
            startFloatingService(VideoFloatingService.TYPE_CAPTURE_SCREEN);
        }
    }

    /**
     * 启动悬浮窗服务
     * @param type
     */
    private void startFloatingService(int type) {
        Intent intent = new Intent(context, VideoFloatingService.class);
        intent.putExtra("type", type);
        context.bindService(intent, serviceConn, Context.BIND_AUTO_CREATE);

        // 共享屏幕时, 如果正在投屏, 则不主动切换到后台
        if (type == VideoFloatingService.TYPE_SHARE_SCREEN_TO_REMOTE && MainActivity.IS_HDMI_CASTING) {
            return;
        }
        getActivity().moveTaskToBack(true);
    }

    /**
     * 停止悬浮窗服务
     */
    public void stopFloatingService() {
        try {
            context.unbindService(serviceConn);
            ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            activityManager.moveTaskToFront(getActivity().getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
        } catch (Exception e) {
            LogUtils.getInstance().e(TAG, e.getMessage());
        } finally {
            binder = null;
        }
    }

    /**
     * 执行截屏操作
     */
    public void captureScreen() {
        if (mediaProjection == null) {
            return;
        }

        Display display = getActivity().getWindowManager().getDefaultDisplay();
        DisplayMetrics realMetrics = new DisplayMetrics();
        display.getRealMetrics(realMetrics);
        final int screenWidth = realMetrics.widthPixels;
        final int screenHeight = realMetrics.heightPixels;

        final ImageReader imageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2);
        final VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay(
                "capture-screen", screenWidth, screenHeight, realMetrics.densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, imageReader.getSurface(), null, null);
        msgHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Image image = imageReader.acquireLatestImage();
                if (image == null) {
                    return;
                }
                if (binder == null) {
                    return;
                }

                try {
                    Image.Plane[] planes = image.getPlanes();
                    ByteBuffer buffer = planes[0].getBuffer();
                    int width = image.getWidth(); // 每行的像素总数
                    // int height = image.getHeight(); // 每列的像素总数
                    int pixelWidth = planes[0].getPixelStride(); // 单个像素的宽度
                    int rowWidth = planes[0].getRowStride(); // 每行的总宽度 = 每行的像素总数 * 单个像素的宽度 + 左右边距
                    int rowPadding = rowWidth - width * pixelWidth; // 左右边距

                    Bitmap bitmap = Bitmap.createBitmap(screenWidth + rowPadding/pixelWidth, screenHeight, Bitmap.Config.ARGB_8888);
                    bitmap.copyPixelsFromBuffer(buffer);

                    // 预览截屏内容
                    binder.previewScreenshot(bitmap);
                } catch (Exception e) {
                    LogUtils.getInstance().e(TAG, e.getMessage());
                } finally {
                    LogUtils.getInstance().closeQuietly(image);
                    virtualDisplay.release();
                }
            }
        }, 500);
    }

    /**
     * 保存截屏图像
     * @param bitmap
     */
    public void saveCaptureScreen(Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }

        FileOutputStream fos = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String timeStr = format.format(new Date());
            String fileName = "screen_shot_" + timeStr + ".png";
            String imgFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + fileName;
            File dir = new File(imgFilePath).getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }

            fos = new FileOutputStream(imgFilePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

            Toast.makeText(context, "已保存到 " + imgFilePath, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            LogUtils.getInstance().e(TAG, e.getMessage());
        } finally {
            LogUtils.getInstance().closeQuietly(fos);
        }
    }

    /**
     * 准备共享屏幕 - 申请共享屏幕权限
     */
    public void prepareShareScreen() {
        LogUtils.getInstance().i(TAG, "prepareShareScreen begin.");

        if (mediaProjectionManager == null || mediaProjection == null) {
            // 申请共享屏幕权限
            mediaProjectionManager = (MediaProjectionManager)context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            Intent intent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(intent, AppConstants.REQUEST_SHARE_SCREEN_CODE);
        } else {
            reqShareScreenFloatingPermission();
        }

        LogUtils.getInstance().i(TAG, "prepareShareScreen end.");
    }

    /**
     * 准备共享屏幕 - 申请悬浮窗权限
     */
    private void reqShareScreenFloatingPermission() {
        if (!Settings.canDrawOverlays(context)) {
            // 申请悬浮窗权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            startActivityForResult(intent, AppConstants.REQUEST_SHARE_FLOATING_CODE);
        } else {
            startFloatingService(VideoFloatingService.TYPE_SHARE_SCREEN);
        }
    }

    /**
     * 准备共享屏幕给远端 - 选择接收 or 发送
     */
    public void prepareShareScreenToRemote() {
        LogUtils.getInstance().i(TAG, "prepareShareScreenToRemote begin.");

        // 弹出对话框选择屏幕共享的方式: 接收 or 发送 or 取消
        AlertDialog.Builder selectDialog = new AlertDialog.Builder(context);
        selectDialog.setTitle("提示").setMessage("您要发送还是接收屏幕共享内容？");
        selectDialog.setNeutralButton("接收", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                prepareRecvShareScreen();
            }
        });
        selectDialog.setNegativeButton("发送", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                prepareSendShareScreen();
            }
        });
        selectDialog.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消操作不涉及业务处理
            }
        });
        selectDialog.show();

        LogUtils.getInstance().i(TAG, "prepareShareScreenToRemote end.");
    }

    /**
     * 准备接收客户端发送过来的屏幕共享内容
     */
    private void prepareRecvShareScreen() {
        final LinearLayout mainPanel = getActivity().findViewById(R.id.mainPanel);

        WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics realMetrics = new DisplayMetrics();
        display.getRealMetrics(realMetrics);
        int screenWidth = realMetrics.widthPixels;
        int screenHeight = realMetrics.heightPixels;

        this.receiverTask = new ReceiverTask("0.0.0.0", AppConstants.SHARE_SCREEN_LISTENER_PORT, this.receiverQueue);
        this.decoderTask = new AvcDecoderTask(screenWidth, screenHeight, 15, this.receiverQueue);
        this.decoderTask.setMsgHandler(msgHandler);

        // 初始化屏幕共享接收界面
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.share_screen_receiver_view, null);
        SurfaceView recvSurfaceview = view.findViewById(R.id.shareScreenRecvSurfaceview);
        recvSurfaceview.getHolder().addCallback(new ShareScreenRecvSurfaceCallback(receiverTask, decoderTask));

        // 给返回按钮绑定事件
        Button stopBtn = view.findViewById(R.id.shareScreenRecvStopBtn);
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 停止接收屏幕共享内容
                VideoFragment.this.decoderTask = null;
                VideoFragment.this.receiverTask = null;
                VideoFragment.this.receiverQueue.clear();
                mainPanel.removeViewAt(0);
                LogUtils.getInstance().i(TAG, "stop receive share screen data success.");
            }
        });

        mainPanel.addView(view, 0);
    }

    /**
     * 准备发送屏幕共享内容给远端 - 申请共享屏幕权限
     */
    private void prepareSendShareScreen() {
        // 获取远端IP -> 校验IP -> 限制本机IP
        String ip = this.remoteIp.getText().toString().trim();
        if (!ip.matches("^([\\d]{1,3}\\.){3}[\\d]{1,3}$")
                || ip.equals("0.0.0.0") || ip.equals("127.0.0.1") || ip.equals("255.255.255.255")) {
            Toast.makeText(context, "无效的对端IP", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mediaProjectionManager == null || mediaProjection == null) {
            // 申请共享屏幕权限
            mediaProjectionManager = (MediaProjectionManager)context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
            Intent intent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(intent, AppConstants.REQUEST_SHARE_TO_REMOTE_CODE);
        } else {
            reqShareScreenSendFloatingPermission();
        }
    }

    /**
     * 准备共享屏幕给远端 - 申请悬浮窗权限
     */
    private void reqShareScreenSendFloatingPermission() {
        if (!Settings.canDrawOverlays(context)) {
            // 申请悬浮窗权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            startActivityForResult(intent, AppConstants.REQUEST_SHARE_TO_REMOTE_FLOATING_CODE);
        } else {
            startFloatingService(VideoFloatingService.TYPE_SHARE_SCREEN_TO_REMOTE);
        }
    }

    /**
     * 开始共享屏幕给远端
     */
    public void startShareScreenSend() {
        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                String remoteIpStr = remoteIp.getText().toString().trim();
                if (!NetworkUtils.isAvailable(remoteIpStr, AppConstants.SHARE_SCREEN_LISTENER_PORT)) {
                    Message msg = Message.obtain();
                    msg.what = MsgHandler.SHOW_TOAST;
                    msg.obj = "接收端服务不可用 " + remoteIpStr;
                    msgHandler.sendMessage(msg);
                }

                // 获取屏幕内容 -> 编码 -> 发送到远端
                WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
                Display display = windowManager.getDefaultDisplay();
                DisplayMetrics realMetrics = new DisplayMetrics();
                display.getRealMetrics(realMetrics);
                int screenWidth = realMetrics.widthPixels;
                int screenHeight = realMetrics.heightPixels;

                // 准备编码及发送任务
                VideoFragment.this.encoderTask = new AvcEncoderTask(screenWidth, screenHeight, 15, VideoFragment.this.senderQueue);
                VideoFragment.this.senderTask = new SenderTask(remoteIpStr, AppConstants.SHARE_SCREEN_LISTENER_PORT, VideoFragment.this.senderQueue);
                final Surface inputSurface = VideoFragment.this.encoderTask.initEncoder();

                // 启动任务
                ThreadPools.run(VideoFragment.this.encoderTask);
                ThreadPools.run(VideoFragment.this.senderTask);

                // 开始获取屏幕内容
                VideoFragment.this.shareScreenSendVirtualDisplay = mediaProjection.createVirtualDisplay(
                        "share-screen", screenWidth, screenHeight, realMetrics.densityDpi,
                        DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, inputSurface, null, null);
                LogUtils.getInstance().i(TAG, "startShareScreenSend success.");
            }
        });
    }

    /**
     * 停止共享屏幕给远端
     */
    public void stopShareScreenSend() {
        if (this.shareScreenSendVirtualDisplay != null) {
            this.shareScreenSendVirtualDisplay.release();
            this.shareScreenSendVirtualDisplay = null;
        }
        ThreadPools.run(new Runnable() {
            @Override
            public void run() {
                if (encoderTask != null) {
                    encoderTask.stop();
                }
                if (senderTask != null) {
                    senderTask.stop();
                }
                if (senderQueue != null) {
                    senderQueue.clear();
                }
            }
        });
    }

    /**
     * 授权之后开始共享屏幕
     */
    public void startShareScreen(int width, int height, int dpi, Surface inputSurface) {
        // 开始共享屏幕
        this.shareScreenVirtualDisplay = mediaProjection.createVirtualDisplay(
                "share-screen", width, height, dpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, inputSurface, null, null);
    }

    /**
     * 停止屏幕共享
     */
    public void stopShareScreen() {
        if (this.shareScreenVirtualDisplay != null) {
            this.shareScreenVirtualDisplay.release();
            this.shareScreenVirtualDisplay = null;
        }
    }

    /**
     * 应用授权结果
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == AppConstants.REQUEST_CAPTURE_SCREEN_CODE) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT).show();
                return;
            }

            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            reqCaptureScreenFloatingPermission();
        } else if (requestCode == AppConstants.REQUEST_CAPTURE_FLOATING_CODE) {
            if (!Settings.canDrawOverlays(context)) {
                Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT).show();
                return;
            }

            startFloatingService(VideoFloatingService.TYPE_CAPTURE_SCREEN);
        } else if (requestCode == AppConstants.REQUEST_SHARE_SCREEN_CODE || requestCode == AppConstants.REQUEST_SHARE_TO_REMOTE_CODE) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT).show();
                return;
            }

            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            if (requestCode == AppConstants.REQUEST_SHARE_SCREEN_CODE) {
                reqShareScreenFloatingPermission();
            } else {
                reqShareScreenSendFloatingPermission();
            }
        } else if (requestCode == AppConstants.REQUEST_SHARE_FLOATING_CODE || requestCode == AppConstants.REQUEST_SHARE_TO_REMOTE_FLOATING_CODE) {
            if (!Settings.canDrawOverlays(context)) {
                Toast.makeText(context, "授权失败", Toast.LENGTH_SHORT).show();
                return;
            }

            if (requestCode == AppConstants.REQUEST_SHARE_FLOATING_CODE) {
                startFloatingService(VideoFloatingService.TYPE_SHARE_SCREEN);
            } else {
                startFloatingService(VideoFloatingService.TYPE_SHARE_SCREEN_TO_REMOTE);
            }
        }
    }

    @Override
    public void onDestroy() {
        if (this.mediaProjection != null) {
            this.mediaProjection.stop();
            this.mediaProjection = null;
        }
        super.onDestroy();
    }
}
